package baseFx.common.caching.redis;

import baseFx.common.collections.redis.RedisList;
import redis.clients.jedis.Jedis;

import java.util.*;

public class RedisListCache<E> extends RedisList<E> {
    private long expireTime;
    private int expire;
    private String name;
    private Jedis jedis;

    public RedisListCache(Jedis jedis, Class<E> clazz, String name, int expireSecond) {
        super(jedis, clazz, name);
        this.name = name;
        this.jedis = jedis;
        this.expire = expireSecond;
    }

    private void resetExpire() {
        if (expireTime > System.currentTimeMillis()) {
            return;
        }
        long value = jedis.ttl(name);
        if (value < 1) {
            jedis.expire(name, expire);
            value = expire;
        }
        this.expireTime = System.currentTimeMillis() + value * 1000;
    }

    @Override
    public boolean addAll(int index, Collection<? extends E> c) {
        boolean b = super.addAll(index, c);
        resetExpire();
        return b;
    }

    @Override
    public boolean addAll(Collection<? extends E> c) {
        boolean b = super.addAll(c);
        resetExpire();
        return b;
    }

    @Override
    public boolean add(E e) {
        boolean b = super.add(e);
        resetExpire();
        return b;
    }
}
